import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import '../../shared/models/word.dart';
import '../../shared/providers/word_provider.dart';
import 'word_detail_page.dart';

// 收藏单词列表Provider - 需要autoDispose以监听favoriteWordsProvider变化
final starredWordsListProvider = FutureProvider.autoDispose<List<Word>>((ref) async {
  // 监听刷新触发器
  ref.watch(starredRefreshProvider);
  final favoriteIds = ref.watch(favoriteWordsProvider);
  final wordService = ref.watch(wordServiceProvider);
  
  final List<Word> starredWords = [];
  for (final id in favoriteIds) {
    final word = await wordService.getWordById(id);
    if (word != null) {
      starredWords.add(word);
    }
  }
  return starredWords;
});

// 收藏统计Provider - 需要autoDispose以跟随starredWordsListProvider
final starredStatsProvider = Provider.autoDispose<Map<String, int>>((ref) {
  final starredWordsAsync = ref.watch(starredWordsListProvider);
  
  return starredWordsAsync.when(
    data: (words) {
      final stats = <String, int>{};
      for (final word in words) {
        stats[word.category] = (stats[word.category] ?? 0) + 1;
      }
      return {
        'total': words.length,
        'categories': stats.length,
        ...stats,
      };
    },
    loading: () => {'total': 0, 'categories': 0},
    error: (_, __) => {'total': 0, 'categories': 0},
  );
});

class FavoritesPage extends ConsumerStatefulWidget {
  const FavoritesPage({super.key});

  @override
  ConsumerState<FavoritesPage> createState() => _FavoritesPageState();
}

class _FavoritesPageState extends ConsumerState<FavoritesPage> with WidgetsBindingObserver {
  String _searchQuery = '';
  String _selectedCategory = 'All';
  bool _showSearch = false;
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _searchController.dispose();
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // 当应用重新获得焦点时，刷新收藏数据
      ref.read(starredRefreshProvider.notifier).state++;
    }
  }

  @override
  Widget build(BuildContext context) {
    final starredWordsAsync = ref.watch(starredWordsListProvider);
    final starredStats = ref.watch(starredStatsProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text(_showSearch ? 'Search Starred' : 'My Starred'),
        centerTitle: true,
        elevation: 0,
        backgroundColor: Colors.amber.shade600,
        foregroundColor: Colors.white,
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                Colors.amber.shade600,
                Colors.amber.shade800,
              ],
            ),
          ),
        ),
        leading: Container(
          margin: const EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: Colors.white.withOpacity(0.1),
            borderRadius: BorderRadius.circular(12),
          ),
          child: IconButton(
            icon: const FaIcon(
              FontAwesomeIcons.arrowLeft,
              color: Colors.white,
              size: 18,
            ),
            onPressed: () => Navigator.pop(context),
          ),
        ),
        actions: [
          Container(
            margin: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.1),
              borderRadius: BorderRadius.circular(12),
            ),
            child: IconButton(
              icon: FaIcon(
                _showSearch ? FontAwesomeIcons.xmark : FontAwesomeIcons.magnifyingGlass,
                color: Colors.white70,
                size: 18,
              ),
              onPressed: () {
                setState(() {
                  _showSearch = !_showSearch;
                  if (!_showSearch) {
                    _searchQuery = '';
                    _searchController.clear();
                  }
                });
              },
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          if (_showSearch) _buildSearchBar(),
          _buildStatsCard(starredStats),
          _buildCategoryFilter(),
          Expanded(
            child: starredWordsAsync.when(
              data: (words) => _buildStarredList(words),
              loading: () => const Center(child: CircularProgressIndicator()),
              error: (error, stackTrace) => _buildErrorState(),
            ),
          ),
        ],
      ),

    );
  }

  Widget _buildSearchBar() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Colors.amber.shade600,
            Colors.amber.shade800,
          ],
        ),
      ),
      child: TextField(
        controller: _searchController,
        style: const TextStyle(color: Colors.white),
        decoration: InputDecoration(
          hintText: 'Search your starred words...',
          hintStyle: TextStyle(color: Colors.white.withOpacity(0.7)),
          prefixIcon: const Icon(Icons.search, color: Colors.white70),
          filled: true,
          fillColor: Colors.white.withOpacity(0.1),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide.none,
          ),
          contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        ),
        onChanged: (value) {
          setState(() {
            _searchQuery = value.toLowerCase();
          });
        },
      ),
    );
  }

  Widget _buildStatsCard(Map<String, int> stats) {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Colors.amber.shade100,
            Colors.amber.shade200,
          ],
        ),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.amber.withOpacity(0.3),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.amber.shade600,
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const FaIcon(
                  FontAwesomeIcons.solidStar,
                  color: Colors.white,
                  size: 20,
                ),
              ),
              const SizedBox(width: 16),
              const Text(
                'Starred Overview',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                  'Total Words',
                  '${stats['total'] ?? 0}',
                  FontAwesomeIcons.solidStar,
                  Colors.amber.shade600,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildStatItem(
                  'Categories',
                  '${stats['categories'] ?? 0}',
                  FontAwesomeIcons.layerGroup,
                  Colors.amber.shade700,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon, Color color) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.7),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        children: [
          FaIcon(icon, color: color, size: 16),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildCategoryFilter() {
    final starredWordsAsync = ref.watch(starredWordsListProvider);
    
    return starredWordsAsync.when(
      data: (words) {
        final categories = words.map((word) => word.category).toSet().toList();
        categories.sort();
        
        if (categories.length <= 1) return const SizedBox();
        
        return Container(
          height: 50,
          margin: const EdgeInsets.symmetric(horizontal: 16),
          child: ListView(
            scrollDirection: Axis.horizontal,
            children: [
              FilterChip(
                label: const Text('All'),
                selected: _selectedCategory == 'All',
                onSelected: (selected) {
                  if (selected) {
                    setState(() {
                      _selectedCategory = 'All';
                    });
                  }
                },
                selectedColor: Colors.amber.shade200,
                backgroundColor: Colors.grey.shade200,
              ),
              const SizedBox(width: 8),
              ...categories.map((category) => Padding(
                padding: const EdgeInsets.only(right: 8),
                child: FilterChip(
                  label: Text(category),
                  selected: _selectedCategory == category,
                  onSelected: (selected) {
                    if (selected) {
                      setState(() {
                        _selectedCategory = category;
                      });
                    }
                  },
                  selectedColor: Colors.amber.shade200,
                  backgroundColor: Colors.grey.shade200,
                ),
              )),
            ],
          ),
        );
      },
      loading: () => const SizedBox(),
      error: (_, __) => const SizedBox(),
    );
  }

  Widget _buildStarredList(List<Word> words) {
    List<Word> filteredWords = words;
    
    // 应用搜索过滤
    if (_searchQuery.isNotEmpty) {
      filteredWords = words.where((word) {
        return word.esperanto.toLowerCase().contains(_searchQuery) ||
               word.english.toLowerCase().contains(_searchQuery) ||
               word.definition.toLowerCase().contains(_searchQuery);
      }).toList();
    }
    
    // 应用分类过滤
    if (_selectedCategory != 'All') {
      filteredWords = filteredWords.where((word) => word.category == _selectedCategory).toList();
    }
    
    if (filteredWords.isEmpty) {
      return _buildEmptyState();
    }
    
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: filteredWords.length,
      itemBuilder: (context, index) {
        final word = filteredWords[index];
        return _buildWordCard(word);
      },
    );
  }

  Widget _buildWordCard(Word word) {
    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      child: Card(
        elevation: 2,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        child: InkWell(
          borderRadius: BorderRadius.circular(16),
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => WordDetailPage(wordId: word.id),
              ),
            );
          },
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Text(
                        word.esperanto,
                        style: const TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                    Stack(
                      children: [
                        IconButton(
                          onPressed: () {
                            ref.read(favoriteWordsProvider.notifier).toggleFavorite(word.id);
                            ref.read(starredRefreshProvider.notifier).state++;
                          },
                          icon: const FaIcon(
                            FontAwesomeIcons.solidStar,
                            color: Colors.amber,
                            size: 20,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
                Text(
                  word.english,
                  style: const TextStyle(
                    fontSize: 16,
                    color: Colors.blue,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                const SizedBox(height: 12),
                if (word.pronunciation.isNotEmpty) ...[
                  Text(
                    '[${word.pronunciation}]',
                    style: TextStyle(
                      fontSize: 14,
                      fontStyle: FontStyle.italic,
                      color: Colors.grey[500],
                    ),
                  ),
                  const SizedBox(height: 8),
                ],
                Text(
                  word.definition,
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[700],
                    height: 1.4,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 12),
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: Colors.amber.withOpacity(0.1),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Text(
                        word.category,
                        style: const TextStyle(
                          fontSize: 12,
                          color: Colors.amber,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: _getDifficultyColor(word.difficulty).withOpacity(0.1),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          FaIcon(
                            FontAwesomeIcons.signal,
                            size: 10,
                            color: _getDifficultyColor(word.difficulty),
                          ),
                          const SizedBox(width: 4),
                          Text(
                            'Level ${word.difficulty}',
                            style: TextStyle(
                              fontSize: 12,
                              color: _getDifficultyColor(word.difficulty),
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Color _getDifficultyColor(int difficulty) {
    switch (difficulty) {
      case 1:
        return Colors.green;
      case 2:
        return Colors.orange;
      case 3:
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FaIcon(
            _searchQuery.isNotEmpty 
                ? FontAwesomeIcons.magnifyingGlass 
                : FontAwesomeIcons.star,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            _searchQuery.isNotEmpty 
                ? 'No matching starred words found'
                : 'No starred words yet',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Colors.grey[600],
            ),
          ),
          const SizedBox(height: 8),
          Text(
            _searchQuery.isNotEmpty 
                ? 'Try adjusting your search terms'
                : 'Start adding words to your starred collection!',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey[500],
            ),
            textAlign: TextAlign.center,
          ),
          if (_searchQuery.isEmpty) ...[
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: () {
                Navigator.pop(context);
              },
              icon: const FaIcon(FontAwesomeIcons.compass, size: 16),
              label: const Text('Explore Words'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.amber.shade600,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildErrorState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const FaIcon(
            FontAwesomeIcons.triangleExclamation,
            size: 64,
            color: Colors.red,
          ),
          const SizedBox(height: 16),
          const Text(
            'Error loading starred words',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Colors.red,
            ),
          ),
          const SizedBox(height: 8),
          const Text(
            'Please try again later',
            style: TextStyle(
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 24),
          ElevatedButton.icon(
            onPressed: () {
              ref.read(starredRefreshProvider.notifier).state++;
            },
            icon: const FaIcon(FontAwesomeIcons.arrowsRotate, size: 16),
            label: const Text('Retry'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.amber.shade600,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  void _showPracticeDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16),
        ),
        title: Row(
          children: [
            FaIcon(FontAwesomeIcons.solidStar, color: Colors.amber.shade600, size: 20),
            const SizedBox(width: 12),
            const Text('Starred Practice'),
          ],
        ),
        content: const Text(
          'Practice mode for starred words is coming soon!\n\n'
          'For now, you can practice your starred words by going to the word learning section and selecting words from the categories your starred words belong to.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Got it'),
          ),
        ],
      ),
    );
  }
} 